
import os
import stat
import zipfile
import shutil
# import threading


def file_unzip(zip_path=None, dir_path=None, callback_func=None):
    '''文件解压操作'''
    if zip_path and dir_path:
        if zipfile.is_zipfile(zip_path):
            print(' 开始解压 '.center(80, '*'))
            fz = zipfile.ZipFile(zip_path, 'r')
            for file in fz.namelist():
                # 指定解压路径
                fz.extract(file, dir_path)
                # 设置文件权限
                os.chmod(os.path.join(dir_path, file), stat.S_IRWXU)
                # print('解压中:', file)
            print(' 解压完成 '.center(80, '*'))
            fz.close()
            # 删除多余的文件
            if os.path.isdir(os.path.join(dir_path, '__MACOSX')):
                shutil.rmtree(os.path.join(dir_path, '__MACOSX'))

            if callback_func:
                callback_func('解压成功', zip_path)
        else:
            print('*** 解压失败 ***')
            if callback_func:
                callback_func('解压失败')


def file_zip(dir_path='', zip_path='', callback_func=None):
    '''文件压缩操作'''
    if len(dir_path) and len(zip_path):
        print(' 开始压缩 '.center(80, '*'))
        fz = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
        for path, dir_names, file_names in os.walk(dir_path):
            # 可以去掉根目录打包
            fpath = path.replace(dir_path, '')
            for filename in file_names:
                # print('压缩:', os.path.join(path, filename))
                fz.write(os.path.join(path, filename), os.path.join(path, filename))
        fz.close()
        print(' 压缩成功 '.center(80, '*'))
        if callback_func:
            callback_func('压缩成功')
    else:
        print('*** 压缩失败 ***')
        if callback_func:
            callback_func('压缩失败')


def change_symbol(old_symbol='', flag='+'):
    '''字符串特殊符转义替换'''
    if flag == '+':
        old_symbol = old_symbol.replace('(', r'\(')
        old_symbol = old_symbol.replace(')', r'\)')
    elif flag == '-':
        old_symbol = old_symbol.replace(r'\(', '(')
        old_symbol = old_symbol.replace(r'\)', ')')
        old_symbol = old_symbol.replace(r'\&', '&')

    return old_symbol









